package cn.cxl.utils;

import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.BitmapFactory;
import android.graphics.BitmapFactory.Options;
import android.media.ThumbnailUtils;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Environment;
import android.telephony.TelephonyManager;
import android.util.Base64;

import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.Random;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


/**
 * 定义自己常用的工具类
 * @author zf
 *
 */
public class MyUtil {

	/**
	 * 手机正则表达式
	 * @param mobiles
	 * @return boolean
	 */
	public static boolean isPhone(String mobiles) {
		Pattern p = Pattern
				.compile("^(1[0-9])\\d{9}$");
		Matcher m = p.matcher(mobiles);
		return m.matches();
	}
	/**
	 * 隐藏手机号139****3333
	 * @param mobiles
	 * @return boolean
	 */
	public static String phone(String mobiles) {
		return mobiles.replaceAll("(\\d{3})\\d{4}(\\d{4})","$1****$2");
	}
	/**
	 *
	 * @param name
	 * @return boolean
	 */
	public static String name(String name) {
		return name.replaceAll("([\\d\\D]{1})(.*)", "$1**");
	}
	/**
	 * 隐藏微分证139****3333
	 * @param mobiles
	 * @return boolean
	 */
	public static String card(String mobiles) {
		return mobiles.replaceAll("(\\d{4})\\d{10}(\\d{4})","$1**********$2");
	}

	/**
	 * 保存文件  
	 * @param bm
	 * @param fileName
	 * @throws IOException
	 */

	public static File saveFile(Bitmap bm, String fileName) throws IOException {
		String path = "";
		File dirFile = new File(path);
		if(!dirFile.exists()){
			dirFile.mkdir();
		}
		File myCaptureFile = new File(path, fileName);
		BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(myCaptureFile));
		bm.compress(CompressFormat.JPEG, 80, bos);
		bos.flush();
		bos.close();
		return myCaptureFile;
	}
	/**
	 * 判断SD卡获取目录
	 * @return
	 */
	public static String getSDPath(){
		File sdDir = null;
		boolean sdCardExist = Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED); //判断sd卡是否存在
		if (sdCardExist)
		{
			sdDir = Environment.getExternalStorageDirectory();//获取跟目录
		}
		return sdDir.toString();
	}
	/**
	 * 判断SD可用不
	 * @return
	 */
	public static boolean hasSdcard(){
		String state = Environment.getExternalStorageState();
		if(state.equals(Environment.MEDIA_MOUNTED)){
			return true;
		}else{
			return false;
		}
	}
	/**
	 * 压缩图片用ThumbnailUtils
	 *
	 */
	public static Bitmap thumbnailBitmap(Bitmap bitmap, int reqsW, int reqsH){
		int old_width = bitmap.getWidth();
		int old_height = bitmap.getHeight();
		// 计算，目标是300*400
		int ratio_width = reqsW;
		int ratio_height = reqsH;
		// 新宽、高
		int new_width = 0;
		int new_height = 0;
		// 缩放参考策略
		if (old_width * ratio_height > old_height * ratio_width) {
			new_width = ratio_width;
			new_height = old_height * ratio_width / old_width;
		} else {
			new_height = ratio_height;
			new_width = old_width * ratio_height / old_height;
		}
		Bitmap new_bitmap = ThumbnailUtils.extractThumbnail(
				bitmap, new_width, new_height);
		return new_bitmap;
	}

	public static Bitmap thumbnailBitmap(Bitmap bitmap){
		int old_width = bitmap.getWidth();
		int old_height = bitmap.getHeight();
		// 计算，目标是300*400
		int ratio_width = 680;
		int ratio_height = 800;
		// 新宽、高
		int new_width = 0;
		int new_height = 0;
		// 缩放参考策略
		if (old_width * ratio_height > old_height * ratio_width) {
			new_width = ratio_width;
			new_height = old_height * ratio_width / old_width;
		} else {
			new_height = ratio_height;
			new_width = old_width * ratio_height / old_height;
		}
		Bitmap new_bitmap = ThumbnailUtils.extractThumbnail(
				bitmap, new_width, new_height);
		return new_bitmap;
	}
	/**
	 * uuid
	 */
	public static String getUUID(){
		return UUID.randomUUID().toString().replace("-", "");
	}


	/**
	 * 读取本地图片
	 *
	 * @param dst
	 * @param width
	 * @param height
	 * @return
	 */
	@SuppressWarnings("deprecation")
	public static Bitmap getBitmapFromFile(File dst, int width, int height) {
		if (null != dst && dst.exists()) {
			Options opts = null;
			if (width > 0 && height > 0) {
				opts = new Options();
				opts.inJustDecodeBounds = true;
				BitmapFactory.decodeFile(dst.getPath(), opts);
				// 计算图片缩放比例
				final int minSideLength = Math.min(width, height);
				opts.inSampleSize = computeSampleSize(opts, minSideLength, width * height);
				opts.inJustDecodeBounds = false;
				opts.inInputShareable = true;
				opts.inPurgeable = true;
			}
			try {
				return BitmapFactory.decodeFile(dst.getPath(), opts);
			} catch (OutOfMemoryError e) {
				e.printStackTrace();
			}
		}
		return null;
	}

	public static int computeSampleSize(Options options, int minSideLength, int maxNumOfPixels) {
		int initialSize = computeInitialSampleSize(options, minSideLength, maxNumOfPixels);

		int roundedSize;
		if (initialSize <= 8) {
			roundedSize = 1;
			while (true) {
				if (roundedSize >= initialSize)
					return roundedSize;
				roundedSize <<= 1;
			}
		}

		return 8 * ((initialSize + 7) / 8);
	}

	private static int computeInitialSampleSize(Options options, int minSideLength, int maxNumOfPixels) {
		double w = options.outWidth;
		double h = options.outHeight;

		int lowerBound = (maxNumOfPixels == -1) ? 1 : (int) Math.ceil(Math.sqrt(w * h / maxNumOfPixels));
		int upperBound = (minSideLength == -1) ? 128
				: (int) Math.min(Math.floor(w / minSideLength), Math.floor(h / minSideLength));

		if (upperBound < lowerBound) {
			// return1 the larger one when there is no overlapping zone.
			return lowerBound;
		}

		if ((maxNumOfPixels == -1) && (minSideLength == -1)) {
			return 1;
		} else if (minSideLength == -1) {
			return lowerBound;
		} else {
			return upperBound;
		}
	}
	/**
	 * bitmap转为base64
	 * @param bitmap
	 * @return
	 */
	public static String bitmapToBase64(Bitmap bitmap) {

		String result = null;
		ByteArrayOutputStream baos = null;
		try {
			if (bitmap != null) {
				baos = new ByteArrayOutputStream();
				bitmap.compress(CompressFormat.JPEG, 100, baos);

				baos.flush();
				baos.close();

				byte[] bitmapBytes = baos.toByteArray();
				result = Base64.encodeToString(bitmapBytes, Base64.DEFAULT);
			}
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				if (baos != null) {
					baos.flush();
					baos.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return result;
	}



	/**
	 * 获取versionName
	 * @param context
	 * @return
	 */
	public static String getVersion(Context context)
	{
		try {
			PackageInfo pi=context.getPackageManager().getPackageInfo(context.getPackageName(), 0);
			return pi.versionName;
		} catch (PackageManager.NameNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return "";
		}
	}
	/**
	 * 获取versionCode
	 * @param context
	 * @return
	 */
	public static  int getVersionCode(Context context){
		PackageManager packageManager=context.getPackageManager();
		PackageInfo packageInfo;
		int versionCode=0;
		try {
			packageInfo=packageManager.getPackageInfo(context.getPackageName(),0);
			versionCode=packageInfo.versionCode;
		} catch (PackageManager.NameNotFoundException e) {
			e.printStackTrace();
		}
		return versionCode;
	}
	/**
	 * 获取当前手机系统版本号
	 *
	 * @return  系统版本号
	 */
	public static String getSystemVersion() {
		return android.os.Build.VERSION.RELEASE;
	}
	/**
	 * 判断网络有无
	 */
	public static boolean isConn(Context context){
		boolean bisConnFlag=false;
		ConnectivityManager conManager = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo network = conManager.getActiveNetworkInfo();
		if(network!=null){
			bisConnFlag=conManager.getActiveNetworkInfo().isAvailable();
		}
		return bisConnFlag;
	}
	// 校验18位身份证号码
	public static boolean isIDCard18(final String value) {
		if (value == null || value.length() != 18)
			return false;
		if (!value.matches("[\\d]+[X]?"))
			return false;
		String code = "10X98765432";
		int weight[] = new int[] { 7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5,
				8, 4, 2, 1 };
		int nSum = 0;
		for (int i = 0; i < 17; ++i) {
			nSum += (int) (value.charAt(i) - '0') * weight[i];
		}
		int nCheckNum = nSum % 11;
		char chrValue = value.charAt(17);
		char chrCode = code.charAt(nCheckNum);
		if (chrValue == chrCode)
			return true;
		if (nCheckNum == 2 && (chrValue + ('a' - 'A') == chrCode))
			return true;
		return false;
	}
	private static long lastClickTime;
	public synchronized static boolean isFastClick() {
		long time = System.currentTimeMillis();
		if ( time - lastClickTime < 1000) {
			return true;
		}
		lastClickTime = time;
		return false;
	}

	/**
	 * imei
	 * @param context
	 * @return
	 */
	public static String getIMEI(Context context){
		TelephonyManager mTm = (TelephonyManager)context.getSystemService(Context.TELEPHONY_SERVICE);
		String imei = mTm.getDeviceId();//imei
		return imei;
	}
	/**
	 * 复制单个文件
	 * @return boolean
	 */
	public static boolean copyFile(String srcFileName, String destFileName)
			throws IOException {
		File srcFile = new File(srcFileName);
		File destFile = new File(destFileName);
		try {
			InputStream inStream = new FileInputStream(srcFile);
			FileOutputStream outStream = new FileOutputStream(destFile);
			byte[] buf = new byte[1024];
			int byteRead = 0;
			while ((byteRead = inStream.read(buf)) != -1) {
				outStream.write(buf, 0, byteRead);
			}
			outStream.flush();
			outStream.close();
			inStream.close();
		} catch (IOException e) {
			return false;
//			throw e;
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
		return true;
	}
	public static byte[] setByte(byte[] byte_1,byte[] byte_2){
		byte[] byte_3 = new byte[byte_1.length+byte_2.length];
		System.arraycopy(byte_1, 0, byte_3, 0, byte_1.length);
		System.arraycopy(byte_2, 0, byte_3, byte_1.length, byte_2.length);
		return byte_3;
	}
	public static String getOrder(){
		return new Date().getTime()+""+new Random().nextInt(100);
	}
	/**
	 * 验证ip是否合法
	 *
	 * @param text
	 *            ip地址
	 * @return 验证信息
	 */
	public static  boolean ipCheck(String text) {
			// 定义正则表达式
			String regex = "^(1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|[1-9])\\."
					+ "(1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|\\d)\\."
					+ "(1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|\\d)\\."
					+ "(1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|\\d)$";
			// 判断ip地址是否与正则表达式匹配
			if (text.matches(regex)) {
				// 返回判断信息
				return true;
			} else {
				// 返回判断信息
				return false;
			}
		}
	/**
	 * 检测邮箱地址是否合法
	 * @param email
	 * @return true合法 false不合法
	 */
	public static  boolean isEmail(String email){
		if (null==email || "".equals(email)) return false;
//        Pattern p = Pattern.compile("\\w+@(\\w+.)+[a-z]{2,3}"); //简单匹配
		Pattern p =  Pattern.compile("\\w+([-+.]\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*");//复杂匹配
		Matcher m = p.matcher(email);
		return m.matches();
	}


	/**
	 * 身份证正则表达式
	 * @param IDNumber
	 * @return
	 */
	public static boolean isIDNumber(String IDNumber) {
		if (IDNumber == null || "".equals(IDNumber)) {
			return false;
		}
		// 定义判别用户身份证号的正则表达式（15位或者18位，最后一位可以为字母）
		String regularExpression = "(^[1-9]\\d{5}(18|19|20)\\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\\d{3}[0-9Xx]$)|" +
				"(^[1-9]\\d{5}\\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\\d{3}$)";
		//假设18位身份证号码:41000119910101123X  410001 19910101 123X
		//^开头
		//[1-9] 第一位1-9中的一个      4
		//\\d{5} 五位数字           10001（前六位省市县地区）
		//(18|19|20)                19（现阶段可能取值范围18xx-20xx年）
		//\\d{2}                    91（年份）
		//((0[1-9])|(10|11|12))     01（月份）
		//(([0-2][1-9])|10|20|30|31)01（日期）
		//\\d{3} 三位数字            123（第十七位奇数代表男，偶数代表女）
		//[0-9Xx] 0123456789Xx其中的一个 X（第十八位为校验值）
		//$结尾

		//假设15位身份证号码:410001910101123  410001 910101 123
		//^开头
		//[1-9] 第一位1-9中的一个      4
		//\\d{5} 五位数字           10001（前六位省市县地区）
		//\\d{2}                    91（年份）
		//((0[1-9])|(10|11|12))     01（月份）
		//(([0-2][1-9])|10|20|30|31)01（日期）
		//\\d{3} 三位数字            123（第十五位奇数代表男，偶数代表女），15位身份证不含X
		//$结尾


		boolean matches = IDNumber.matches(regularExpression);

		//判断第18位校验值
		if (matches) {

			if (IDNumber.length() == 18) {
				try {
					char[] charArray = IDNumber.toCharArray();
					//前十七位加权因子
					int[] idCardWi = {7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2};
					//这是除以11后，可能产生的11位余数对应的验证码
					String[] idCardY = {"1", "0", "X", "9", "8", "7", "6", "5", "4", "3", "2"};
					int sum = 0;
					for (int i = 0; i < idCardWi.length; i++) {
						int current = Integer.parseInt(String.valueOf(charArray[i]));
						int count = current * idCardWi[i];
						sum += count;
					}
					char idCardLast = charArray[17];
					int idCardMod = sum % 11;
					if (idCardY[idCardMod].toUpperCase().equals(String.valueOf(idCardLast).toUpperCase())) {
						return true;
					} else {
						System.out.println("身份证最后一位:" + String.valueOf(idCardLast).toUpperCase() +
								"错误,正确的应该是:" + idCardY[idCardMod].toUpperCase());
						return false;
					}

				} catch (Exception e) {
					e.printStackTrace();
					System.out.println("异常:" + IDNumber);
					return false;
				}
			}

		}
		return matches;
	}

}
